<?php
namespace zqs\admin\controller;
use think\facade\Filesystem;
use zqs\admin\model\Attachment;

class Upload extends Admin
{
    protected $noNeedRight = ['*'];
    public function initialize()
    {
        parent::initialize();
        $this->model = new Attachment();
    }
    /**
     * 图片上传
     */
    public function image()
    {
        //默认验证,随后改为数据库配置
        $image_validate = [
            'fileSize' => 2*1024*1024,//2M
            'fileExt' => 'jpg,png,jpeg,gif',
            'fileMime' => 'image/jpeg,image/jpg,image/png,image/gif',
        ];

        //表单名
        $target = input('target','image');

        //保存路径
        $save_path = 'uploads/image';

        //保存磁盘
        $disk = input('disk','');

        return self::upload($image_validate,$target,$save_path,$disk);
    }
    /**
     * 文件上传
     */
    public function file()
    {
        //默认验证,随后改为数据库配置
        $image_validate = [
            'fileSize' => 5*1024*1024,//10M
            'fileExt' => 'mp3,mp4,zip,txt,csv,xls,xlsx',
            'fileMime' => 'audio/mpeg,audio/mp4,aplication/zip,text/plain,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ];

        //表单名
        $target = 'file';

        //保存路径
        $save_path = 'uploads/file';

        //保存磁盘
        $disk = input('disk','');

        return self::upload($image_validate,$target,$save_path,$disk);
    }
    /**
     * 上传
     */
    private function upload($validate,$target,$save_path,$disk='')
    {

        $file = $this->request->file($target);
        if (!$file){
            return $this->error('请选择您要上传的内容');
        }

        //验证
        $ret = $this->validate([$target=>$file], [$target=>$validate]);

        if (true===$ret){
            //存储方式
            if (empty($disk)){
                $disk = config_db('upload_disks')??'public';
            }

            //判断是否已经存在附件
            $sha1 = $file->hash();
            $uploaded = $this->model->where('sha1', $sha1)->find();
            if ($uploaded)
            {
                $data = [
                    'id' => $uploaded['id'],
                    'url' => $uploaded['url'],
                    'name' => $uploaded['name']
                ];
                return $this->success('上传成功','',$data);
            }

            //保存文件
            if ('aliyun'==$disk){
                $config = [
                    'type'         => 'aliyun',
                    'accessId'     => config_db('upload_aliyun_accessId'),
                    'accessSecret' => config_db('upload_aliyun_accessSecret'),
                    'bucket'       => config_db('upload_aliyun_bucket'),
                    'endpoint'     => config_db('upload_aliyun_endpoint'),
                    'url'          => config_db('upload_aliyun_url'),//不要斜杠结尾，此处为URL地址域名。
                ];
                if (count(array_filter($config)) < count($config)){
                    return $this->error('上传配置错误');
                }
                //动态配置
                $file_config = config('filesystem');
                $file_config['disks']['aliyun'] = $config;
                \think\facade\Config::set($file_config,'filesystem');
                //上传
                $savename = \think\facade\Filesystem::disk('aliyun')->putFile($save_path, $file);
                $savename = '/'.$savename;
                $url = $config['url'].$savename;

            }elseif ('qiniu'==$disk){
                $config = [
                    'type'      => 'qiniu',
                    'accessKey' => config_db('upload_qiniu_accessKey'),
                    'secretKey' => config_db('upload_qiniu_secretKey'),
                    'bucket'    => config_db('upload_qiniu_bucket'),
                    'url'       => config_db('upload_qiniu_url'),//不要斜杠结尾，此处为URL地址域名。
                ];
                if (count(array_filter($config)) < count($config)){
                    return $this->error('上传配置错误');
                }
                //动态配置
                $file_config = config('filesystem');
                $file_config['disks']['qiniu'] = $config;
                \think\facade\Config::set($file_config,'filesystem');
                //上传
                $savename = \think\facade\Filesystem::disk('qiniu')->putFile($save_path, $file);
                $savename = '/'.$savename;
                $url = $config['url'].$savename;

            }else{
                $savename = \think\facade\Filesystem::disk('public')->putFile($save_path, $file);
                $url = $savename = config('filesystem.disks.public.url').'/'.$savename;
                //带域名地址
                $url = config('app.app_host').$url;
            }
            //保存文件信息入库
            $imagewidth = $imageheight = 0;
            if (in_array($file->getOriginalExtension(), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
            {
                $imgInfo = getimagesize($file->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'name'        => $file->getOriginalName(),
                'filesize'    => $file->getSize(),
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $file->getOriginalExtension(),
                'imageframes' => 0,
                'mimetype'    => $file->getMime(),
                'url'         => $savename,
                'upload_time' => time(),
                'sha1'        => $sha1,
                'storage'     => $disk,
                'cate_id'     => input('cate_id',0,'intval')
            );

            //入库
            $this->model->save(array_filter($params));

            $data = [
                'id' => $this->model->id,
                'url' => $url,
                'name' => $params['name']
            ];

            return $this->success('上传成功','',$data);
        }else {
            return $this->error($ret['msg']);
        }


    }


















}
